package com.ruoyi.common.utils.mail;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;
import java.util.List;

/**
 * 邮件工具类
 *
 * @author cloudoer
 */
@Component
public class EmailUtils {

    @Value("${spring.mail.username}")
    private String email;

    @Autowired
    private JavaMailSender javaMailSender;

    /**
     * 发送普通文字邮件
     * @param to  收信人
     * @param subject  主题
     * @param content  内容
     */
    public void sendSimpleMail(String to, String subject, String content) {

        SimpleMailMessage message = new SimpleMailMessage();
        message.setTo(to);//收信人
        message.setSubject(subject);//主题
        message.setText(content);//内容
        message.setFrom(email);//发信人

        javaMailSender.send(message);
    }

    /**
     * 发送带HTML代码的邮件
     * @param to
     * @param subject
     * @param content
     * @throws MessagingException
     */
    public void sendHtmlMail(String to, String subject, String content) throws MessagingException {

        //使用MimeMessage，MIME协议
        MimeMessage message = javaMailSender.createMimeMessage();

        MimeMessageHelper helper;
        //MimeMessageHelper帮助我们设置更丰富的内容
        helper = new MimeMessageHelper(message, true);
        helper.setFrom(email);
        helper.setTo(to);
        helper.setSubject(subject);
        helper.setText(content, true);//true代表支持html
        javaMailSender.send(message);
    }

    /**
     * 发送带附件的邮件
     * @param to
     * @param subject
     * @param content
     * @param files
     * @throws MessagingException
     */
    public void sendAttachmentMail(String to, String subject, String content, List<File> files) throws MessagingException {

        MimeMessage message = javaMailSender.createMimeMessage();

        MimeMessageHelper helper;
        helper = new MimeMessageHelper(message, true);
        //true代表支持多组件，如附件，图片等
        helper.setFrom(email);
        helper.setTo(to);
        helper.setSubject(subject);
        helper.setText(content, true);
        for (File file : files){
            FileSystemResource fileSystemResource = new FileSystemResource(file);
            String fileName = fileSystemResource.getFilename();
            helper.addAttachment(fileName, fileSystemResource);//添加附件，可多次调用该方法添加多个附件
        }
        javaMailSender.send(message);

    }
}
